﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseCore
{
    public class GenerateNoDao : IGenerateNoDao
    {
        public int GenerateNo(string key)
        {
            using (var ctx = new ExportDBEntities())
            {
                var generateNo = (from x in ctx.tbl_GenerateNo
                            where x.Key == key
                            select x).FirstOrDefault();

                var runningNo = 1;
                if (generateNo == null)
                {
                    ctx.tbl_GenerateNo.Add(
                        new tbl_GenerateNo()
                        {
                            Key = key,
                            RunningNo = 1
                        });
                }
                else
                {
                    runningNo = generateNo.RunningNo + 1;
                    if (runningNo > 999999)
                    {
                        runningNo = 1;
                    }
                    generateNo.RunningNo = runningNo;
                }

                ctx.SaveChanges();
                return runningNo;
            }
        }
    }
}
